import json
from PyQt5.Qt import *
from PyQt5.Qt import QThread
from PyQt5 import QtCore ,QtWidgets
from PyQt5.QtWidgets import QVBoxLayout,QHBoxLayout,QPushButton,QLabel,QWidget,QApplication
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSignal
import time
import sys
from PyQt5 import uic
import copy
from camera import Camera_Thread

import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

class Window(QWidget):

    gui_signal = pyqtSignal(str)
    server_signal = pyqtSignal(str)
    def __init__(self):
        super().__init__()
        self.msg_history=list()
        self.setup_ui()

    def setup_ui(self):
        #定义一个label控件做为图片的容器
        self.ui = uic.loadUi("/home/cat/Src/mainwindow.ui")

        # 提取要操作的控件    
        self.textBrowser_log = self.ui.textBrowser_log      # 日志显示区
        self.Label_camera = self.ui.label_camera            # 摄像头图片显示区
        self.Button_Stop= self.ui.pushButton_Cstop         # 停止按钮
        self.Button_munul = self.ui.pushButton_mul        # 手动控制按钮
        self.Button_Auto = self.ui.pushButton_auto          # 自动控制按钮

        self.tabWeight = self.ui.tabWidget
        self.Button_reset = self.ui.pushButton_restart
        self.Button_X = self.ui.pushButton_3                # 关闭按钮
        self.Button_min = self.ui.pushButton
        
        self.ui.setWindowIcon(QIcon("./pic/ic.ico"))
        self.Button_min.setStyleSheet("background-color:rgb(19, 13, 81);\n""image:url(./pic/close.png);")
        self.Button_X.setStyleSheet("background-color:rgb(19, 13, 81);\n""image:url(./pic/min.png);")

        # self.label6 = self.ui.label_6                       # 设置标题图标
        # self.label6.setStyleSheet("background-color:rgb(19, 13, 81);\n""image:url(./IOA8.png);")

        self.gui_signal.connect(self.gui_signal_dispatch)

        # 给按钮添加事件（即点击后要调用的函数）
        self.Button_Auto.clicked.connect(self.Button_Auto_clicked)
        self.Button_munul.clicked.connect(self.Button_mumul_clicked)
        self.Button_Stop.clicked.connect(self.Button_stop_clicked)
        self.Button_reset.clicked.connect(self.Button_reset_clicked)

        self.Button_X.clicked.connect(self.Button_X_clicked)
        self.Button_min.clicked.connect(self.Button_min_clicked)
        self.tabWeight.currentChanged.connect(self.tabweight_change)

        ## 二维码移动按钮
        self.ui.pushButton_2.clicked.connect(lambda:self.move_QR(num=1))
        self.ui.pushButton_4.clicked.connect(lambda:self.move_QR(num=2))
        self.ui.pushButton_5.clicked.connect(lambda:self.move_QR(num=3))
        self.ui.pushButton_6.clicked.connect(lambda:self.move_QR(num=4))
        
        ## A,B,C,D,E 移动按钮
        self.ui.pushButton_7.clicked.connect(lambda:self.move_QR(num=5))
        self.ui.pushButton_8.clicked.connect(lambda:self.move_QR(num=6))
        self.ui.pushButton_9.clicked.connect(lambda:self.move_QR(num=7))
        self.ui.pushButton_10.clicked.connect(lambda:self.move_QR(num=8))

        ##  num =  red（有害垃圾） blue（可回收垃圾）purple green（厨卫垃圾） yellow（湿垃圾） orange megt 移动按钮
        self.ui.pushButton_harmful.clicked.connect(lambda:self.move_QR(num=11))
        self.ui.pushButton_recycle.clicked.connect(lambda:self.move_QR(num=12))
        self.ui.pushButton_chuwei.clicked.connect(lambda:self.move_QR(num=14))
        self.ui.pushButton_wet.clicked.connect(lambda:self.move_QR(num=15))

        ## 形状按钮
        self.ui.pushButton_11.clicked.connect(lambda:self.move_QR(num=21))
        self.ui.pushButton_12.clicked.connect(lambda:self.move_QR(num=22)) 
        self.ui.pushButton_13.clicked.connect(lambda:self.move_QR(num=23))
        self.ui.pushButton_14.clicked.connect(lambda:self.move_QR(num=24))

        self.camera = Camera_Thread(self.Label_camera,self.gui_signal)   # 建立摄像头线程
        self.camera.start()
 
    def move_QR(self,num):
        try:
            match num:
                case 1:
                    self.camera.cap_signal.emit(json.dumps({"source":1,}))
                    self.log("正在检测二维码1中....")

                case 2:
                    self.camera.cap_signal.emit(json.dumps({"source":2,}))
                    self.log("正在检测二维码2中....")
                
                case 3:
                    self.camera.cap_signal.emit(json.dumps({"source":3,}))
                    self.log("正在检测二维码3中....")
                
                case 4:
                    self.camera.cap_signal.emit(json.dumps({"source":4,}))
                    self.log("正在检测二维码4中....")
                
                case 5:
                    self.camera.cap_signal.emit(json.dumps({"source":5,}))
                    self.log("正在检测字符A....")                   
                
                case 6:
                    self.camera.cap_signal.emit(json.dumps({"source":6,}))
                    self.log("正在检测字符B....")    

                case 7:
                    self.camera.cap_signal.emit(json.dumps({"source":7,}))
                    self.log("正在检测字符C....")                   

                case 8:
                    self.camera.cap_signal.emit(json.dumps({"source":8,}))
                    self.log("正在检测字符D....")  
                
                case 9:
                    self.camera.cap_signal.emit(json.dumps({"source":9,}))
                    self.log("正在检测字符E....")  
                
                case 11:
                    self.camera.cap_signal.emit(json.dumps({"source":11,}))
                    # self.log("正在检测红色....") 
                    self.log("正在检测有害垃圾....") 

                case 12:
                    self.camera.cap_signal.emit(json.dumps({"source":12,}))
                    # self.log("正在检测蓝色....")
                    self.log("正在检测可回收垃圾....")  

                case 13:
                    self.camera.cap_signal.emit(json.dumps({"source":13,}))
                    self.log("正在检测紫色....")  

                case 14:
                    self.camera.cap_signal.emit(json.dumps({"source":14,}))
                    # self.log("正在检测绿色....")
                    self.log("正在检测厨卫垃圾....")
                
                case 15:
                    self.camera.cap_signal.emit(json.dumps({"source":15,}))
                    # self.log("正在检测黄色....")
                    self.log("正在检测湿垃圾....")  

                case 16:
                    self.camera.cap_signal.emit(json.dumps({"source":16,}))
                    self.log("正在检测橙色....")  
                
                case 17:
                    self.camera.cap_signal.emit(json.dumps({"source":17,}))
                    self.log("正在检测品红色....")  

                case 19:
                    self.camera.cap_signal.emit(json.dumps({"source":19,}))
                    self.log("正在移动至home位置....")  
                
                case 20:
                    self.camera.cap_signal.emit(json.dumps({"source":20,}))
                    self.log("正在移动至拍照位置....")  
                
                case 21:
                    self.camera.cap_signal.emit(json.dumps({"source":21,}))
                    self.log("正在检测.圆形...") 
                
                case 22:
                    self.camera.cap_signal.emit(json.dumps({"source":22,}))
                    self.log("正在检测三角形....") 
                
                case 23:
                    self.camera.cap_signal.emit(json.dumps({"source":23,}))
                    self.log("正在检测六边形....") 
                
                case 24:
                    self.camera.cap_signal.emit(json.dumps({"source":24,}))
                    self.log("正在检测矩形....") 

        except Exception as e:
            logger.error(e,exc_info=True)

    # 切换程序
    def tabweight_change(self,):
        try:
            num =  self.tabWeight.currentIndex()
            match num:
                case 0:
                    self.log("正在切换垃圾分拣程序，请稍后！")
                    self.camera.program_flag = num
                case 1:
                    self.log("正在切换形状检测程序，请稍后！")
                    self.camera.program_flag = num
                case 2:
                    self.log("正在切换二维码检测程序，请稍后！")
                    self.camera.program_flag = num
                case 3:
                    self.log("正在切换OCR检测程序, 此程序使用了一个较大的深度学习模型，计算时间较长，请稍后！")
                    self.camera.program_flag = num

        except Exception as e:
            logger.error(e,exc_info=True)

    def Button_min_clicked(self):
        self.ui.showMinimized()

    # 关闭所有进程
    def Button_X_clicked(self):
        self.ui.close()

    # 复位
    def Button_reset_clicked(self):
        try:
            self.log("仓库已复位")
            self.camera.master.auto_flag = 0
            self.camera.master.action_flag = 0
            # self.camera.master.camera_position = 1
            self.move_QR(num=19)
            
        except Exception as e:
            self.log(f"复位失败，原因是{e}")       
    
    # 停止
    def Button_stop_clicked(self):
        try:
            self.log("停止已按下")
            self.camera.master.auto_flag = 0
            self.camera.master.action_flag = 0

        except Exception as e:
            self.log(f"停止失败，原因是{e}")

    # 自动运行
    def Button_Auto_clicked(self):
        try:
            self.ui.pushButton_2.setEnabled(False)
            self.ui.pushButton_4.setEnabled(False)
            self.ui.pushButton_5.setEnabled(False)
            self.ui.pushButton_6.setEnabled(False)
            self.ui.pushButton_7.setEnabled(False)
            self.ui.pushButton_8.setEnabled(False)
            self.ui.pushButton_9.setEnabled(False)
            self.ui.pushButton_10.setEnabled(False)
            self.ui.pushButton_11.setEnabled(False)

            self.ui.pushButton_12.setEnabled(False)
            self.ui.pushButton_13.setEnabled(False)

            self.camera.master.auto_flag = 1
            self.camera.master.auto_first = 1
            num =  self.tabWeight.currentIndex()
            match num:
                case 0:
                    self.camera.master.action_flag = 11
                case 1:
                    self.camera.master.action_flag = 1
                case 2:
                    self.camera.master.action_flag = 5

        except Exception as e:
            self.log(f"自动运行失败，原因是{e}")

    # 手动运行
    def Button_mumul_clicked(self):
        try:
            self.camera.master.auto_flag = 0
            self.camera.master.camera_position = 1
            self.move_QR(num=20)
            self.ui.pushButton_2.setEnabled(True)
            self.ui.pushButton_4.setEnabled(True)
            self.ui.pushButton_5.setEnabled(True)
            self.ui.pushButton_6.setEnabled(True)
            self.ui.pushButton_7.setEnabled(True)
            self.ui.pushButton_8.setEnabled(True)
            self.ui.pushButton_9.setEnabled(True)
            self.ui.pushButton_10.setEnabled(True)
            self.ui.pushButton_11.setEnabled(True)
            self.ui.pushButton_12.setEnabled(True)
            self.ui.pushButton_13.setEnabled(True)

        except Exception as e:
            self.log(f"手动运行失败，原因是{e}")

    # 信号调度
    def gui_signal_dispatch(self,msg):
        msg = json.loads(msg)
        source = int(msg.get("source"))   # 判断来自哪里的信号
        match source:
            case 0 :
                name = msg.get("name")
                self.log(f"没有检测到{name}")
            case 1 :
                name = msg.get("name")            
                self.log(f"正在抓取{name}，请等待！")
            case 2:
                self.log(f"没有检测到摄像头！")
            
            case 3:
                self.log("自动运行完毕！")

            case 4:
                self.log("请等待机器人就绪！")

            case 5:
                self.log("请等待机器人移动到拍照位置，重新发布指令！") 

            case 6:
                name = msg.get("name")
                self.log(name)      

    # 打印日志
    def log(self,msg):
        msg =time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))+":  "+msg
        self.msg_history.append(msg)
        self.textBrowser_log.setText("<br>".join(self.msg_history))
        self.textBrowser_log.moveCursor(self.textBrowser_log.textCursor().End)
        self.textBrowser_log.repaint()  # 更新内容，如果不更新可能没有显示新内容

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.ui.show()
    app.exec()
